package com.lap.auth.shared.tools;

import org.apache.commons.lang3.StringUtils;

/**
 * <pre>
 * 局域网网段区间判断
 * </pre>
 *
 * @author Shuisheng Lao(劳水生)
 * @version 0.0.1
 */
public enum IpRound {
    ONE("10", 0, 255),
    TWO("172", 16, 31),
    THREE("192", 168, 168),
    ;

    private final String key;

    private final Integer min;

    private final Integer max;

    IpRound(String key, Integer min, Integer max) {
        this.key = key;
        this.min = min;
        this.max = max;
    }

    public static boolean validIp(String ip) {
        if (StringUtils.isBlank(ip)) {
            return true;
        }

        String[] ips = ip.split("\\.");
        if (ips.length != 4) {
            return true;
        }

        try {
            String firstOctet = ips[0];
            int secondOctet = Integer.parseInt(ips[1]);
            for (IpRound ipRound : IpRound.values()) {
                if (ipRound.key.equals(firstOctet)
                        && secondOctet >= ipRound.min
                        && secondOctet <= ipRound.max) {
                    return true;
                }
            }
        } catch (NumberFormatException e) {
            // Ignore non-numeric IP segments
        }
        return false;
    }

}
